package com.mera.tektronix.csviewer.services

import org.apache.commons.logging.LogFactory
import org.springframework.context.MessageSource

import com.mera.tektronix.csviewer.common.api.*
import com.mera.tektronix.csviewer.common.dto.*
import com.mera.tektronix.csviewer.common.exception.LogicException
import com.mera.tektronix.csviewer.domain.*
import com.mera.tektronix.csviewer.jmx.ConfigurationMBean
import com.mera.tektronix.csviewer.transformers.ITransformer

class DepartmentRemoteService implements IDepartmentService {
	static transactional = true
	private static final log = LogFactory.getLog(DepartmentRemoteService.class)
	
	ITransformer departmentTransformer
	MessageSource messageSource
	ConfigurationMBean configurationMBean
	
	@Override
	public List<DepartmentDto> getList() {
		List<Department> departments = Department.list(sort: configurationMBean.classOrders["${Department.class.name}"].sort, order: configurationMBean.classOrders["${Department.class.name}"].order); 
		return departmentTransformer.transformDomainToDtoList(departments);
	}

	@Override
	public DepartmentDto getDepartmentById(Long id) {
		Department dep = Department.get(id);
		return departmentTransformer.transformDomainToDto(dep);
	}

	@Override
	public void addDepartment(DepartmentDto department) throws LogicException {
		Department dep = departmentTransformer.transformDtoToDomain(department);
		
		if(!dep.save()) {
			def err = dep.errors.allErrors.collect {[
						  errorMessage : messageSource.getMessage(it, null)
					  ]}
			
			throw new LogicException(err);
		}

	}

	@Override
	public void deleteDepartment(Long id) {
		Department dep = Department.get(id);
		dep.delete(flush : true);
	}

}
